package com.xof.phonecall.helpipetrpide

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.xof.phonecall.MyApplication
import com.xof.phonecall.R
import com.xof.phonecall.valipetrpide.ValGlobalConstant
import kotlinx.coroutines.Runnable

@SuppressLint("ApplySharedPref")
object GaidHelpipetrpide {
    val VAL_SP_KEY_GAID = MyApplication.context.getString(R.string.SPKeyGaid)
    private var mThreadHandleripetrpide: HandlerThread

    init {
        val spipetrpide = MyApplication.context.getSharedPreferences(ValGlobalConstant.VAL_PRODUCT, Context.MODE_PRIVATE)
        MyApplication.VAL_GAID = spipetrpide.getString(VAL_SP_KEY_GAID, "").toString()

        mThreadHandleripetrpide = HandlerThread("GAID_INIT")
        mThreadHandleripetrpide.start()
    }

    private const val VAL_GAID_INIT = 298
    private const val VAL_TIMER_EACH = 398
    private var mCountipetrpide: Int = 0
    private val mGaidHandleripetrpide: GaidHandler = GaidHandler()
    private val mGaidRunnableipetrpide: Runnable = Runnable {
        mCountipetrpide += 1
        initGaidipetrpide()
    }

    class GaidHandler : Handler(mThreadHandleripetrpide.looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                VAL_GAID_INIT -> {
                    try {
                        val sp = MyApplication.context.getSharedPreferences(ValGlobalConstant.VAL_PRODUCT,
                            Context.MODE_PRIVATE)
                            .edit()
                        sp.putString(VAL_SP_KEY_GAID, MyApplication.VAL_GAID)
                        sp.commit()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                VAL_TIMER_EACH -> {
                    startGaidHandleripetrpide()
                }
            }
        }
    }

    fun initGaidInThreadipetrpide() {
        try {
            Thread {
                println("2===================================")
                try {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        if (MyApplication.VAL_GAID.isBlank()) {
                            val advertisingIdClient =
                                AdvertisingIdClient.getAdvertisingIdInfo(MyApplication.context)
                            val gaid = advertisingIdClient.id
                            val genable = advertisingIdClient.isLimitAdTrackingEnabled
                            println("4===gaid:$gaid , genable:$genable")

                            MyApplication.VAL_GAID = if (gaid.isNullOrBlank()) "" else gaid
                            MyApplication.VAL_IS_LIMIT_AD_TRACKING_ENABLED = if (genable) 1 else 0

                            mGaidHandleripetrpide.sendEmptyMessage(VAL_GAID_INIT)
                        }
                    } else {
                        println("init GAID ERROR!!! Cannot call in the main thread, You must call in the other thread")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun initGaidipetrpide() {
        try {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                println("init GAID ERROR!!! Cannot call in the main thread, You must call in the other thread")
                return
            }

            if (MyApplication.VAL_GAID.isBlank()) {
                val advertisingIdClient =
                    AdvertisingIdClient.getAdvertisingIdInfo(MyApplication.context)
                val gaid = advertisingIdClient.id
                val genable = advertisingIdClient.isLimitAdTrackingEnabled
                println("5===gaid:$gaid , genable:$genable")

                MyApplication.VAL_GAID = if (gaid.isNullOrBlank()) "" else gaid
                MyApplication.VAL_IS_LIMIT_AD_TRACKING_ENABLED = if (genable) 1 else 0
            }

            //如果gaid不为空，渠道不为空，上传
            //如果gaid为不为空，渠道为空, 上传
            //如果gaid为空，渠道不为空，上传
            //如果gaid为空，渠道为空，上传
            if (MyApplication.VAL_GAID.isNotBlank()) {
//                println("6===gaid:${GPReferrerHelpipetrpide.mInstallReferreripetrpide}")
                //GPReferrerHelpipetrpide.connectipetrpide()
            }

            if (MyApplication.VAL_GAID.isBlank()) {
                println("7===================================")
                mGaidHandleripetrpide.sendEmptyMessage(VAL_TIMER_EACH)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun startGaidHandleripetrpide() {
        try {
            //移除回调
            removeHandlerCallbackipetrpide()

            //5次后忽略
            if (mCountipetrpide >= 5) {
                return
            }

            //5秒后执行重推
            mGaidHandleripetrpide.postDelayed(mGaidRunnableipetrpide, 5000)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun removeHandlerCallbackipetrpide() {
        try {
            mGaidHandleripetrpide.removeCallbacks(mGaidRunnableipetrpide)
            mGaidHandleripetrpide.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}